package com.znufe.exam.controller.admin;

import com.znufe.exam.base.BaseApiController;
import com.znufe.exam.base.RestResponse;
import com.znufe.exam.configuration.config.annotation.Log;
import com.znufe.exam.configuration.config.enums.BusinessType;
import com.znufe.exam.configuration.config.model.LoginUser;
import com.znufe.exam.configuration.config.service.TokenService;
import com.znufe.exam.configuration.config.utils.ServletUtils;
import com.znufe.exam.domain.ExamPaper;
import com.znufe.exam.domain.User;
import com.znufe.exam.domain.enums.ExamPaperStatusEnum;
import com.znufe.exam.service.ExamPaperService;
import com.znufe.exam.utility.DateTimeUtil;
import com.znufe.exam.utility.PageInfoHelper;
import com.znufe.exam.viewmodel.admin.exam.*;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@Api(description = "试卷信息",value="试卷信息" )
@RestController("AdminExamPaperController")
@RequestMapping(value = "/api/admin/exam/paper")
@AllArgsConstructor
public class ExamPaperController extends BaseApiController {

    private final ExamPaperService examPaperService;

    @Autowired
    private TokenService tokenService;

    @PreAuthorize("@ss.hasPermi('exam:paper:list')")
    @RequestMapping(value = "/page", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "试卷信息的页面查询接口（无参数查找/按试卷类别查找/按试卷名称查找）",
            notes = "查询试卷信息[t_exam_paper]，作者：lin keqing")
    public RestResponse<PageInfo<ExamResponseVM>> pageList(@RequestBody ExamPaperPageRequestVM model) {
        model = ExamPaperPageRequestVM.wipeBlank(model);
        PageInfo<ExamPaper> pageInfo = examPaperService.page(model);
        PageInfo<ExamResponseVM> page = PageInfoHelper.copyMap(pageInfo, e -> {
            ExamResponseVM vm = modelMapper.map(e, ExamResponseVM.class);
            vm.setCreateTime(DateTimeUtil.dateFormat(e.getCreateTime()));
            return vm;
        });
        return RestResponse.ok(page);
    }


    @RequestMapping(value = "/taskExamPage", method = RequestMethod.POST)
    public RestResponse<PageInfo<ExamResponseVM>> taskExamPageList(@RequestBody ExamPaperPageRequestVM model) {
        PageInfo<ExamPaper> pageInfo = examPaperService.taskExamPage(model);
        PageInfo<ExamResponseVM> page = PageInfoHelper.copyMap(pageInfo, e -> {
            ExamResponseVM vm = modelMapper.map(e, ExamResponseVM.class);
            vm.setCreateTime(DateTimeUtil.dateFormat(e.getCreateTime()));
            return vm;
        });
        return RestResponse.ok(page);
    }

    @PreAuthorize("@ss.hasAnyPermi('exam:paper:add,exam:paper:update')")
    @Log(title = "试卷管理", businessType = BusinessType.EDIT)
    @RequestMapping(value = "/edit", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "试卷信息的编辑接口（新增/更新）",
                  notes = "新增/更新试卷信息[t_exam_paper](更新请传入试卷id)，作者：lin keqing")
    public RestResponse<ExamPaperEditRequestVM> edit(@RequestBody @Valid ExamPaperEditRequestVM model) {
        //当前用户
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        User user = loginUser.getUser();

        ExamPaper examPaper = examPaperService.savePaperFromVM(model, user);
        ExamPaperEditRequestVM newVM = examPaperService.examPaperToVM(examPaper.getId());
        return RestResponse.ok(newVM);
    }

    @PreAuthorize("@ss.hasPermi('exam:paper:query')")
    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "根据id查找试卷(编辑按钮调用这个接口)",notes = "返回部分试卷信息")
    @ApiImplicitParam(paramType="path", name = "id", value = "试卷id", dataType = "int",required = true)
    public RestResponse<ExamPaperEditRequestVM> select(@PathVariable Integer id) {
        ExamPaperEditRequestVM vm = examPaperService.examPaperToVM(id);
        return RestResponse.ok(vm);
    }

    @RequestMapping(value = "/selectQuestionList/{id}", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "根据id查找试卷的题目(答卷按钮使用这个接口)",notes = "返回试卷的题目信息")
    @ApiImplicitParam(paramType="path", name = "id", value = "试卷id", dataType = "int",required = true)
    public  RestResponse<ExamQuestionListResponseVM> selectQuestionList(@PathVariable Integer id) {
        ExamPaperEditRequestVM examPaperEditRequestVM = examPaperService.examPaperToVM(id);
        ExamQuestionListResponseVM vm = modelMapper
                .map(examPaperEditRequestVM, ExamQuestionListResponseVM.class);
        ExamPaperTitleItemVM questionListVM = examPaperEditRequestVM.getTitleItems().get(0);
        vm.setExamName(questionListVM.getName());
        vm.setQuestionItems(questionListVM.getQuestionItems());
        return RestResponse.ok(vm);
    }

    @PreAuthorize("@ss.hasPermi('exam:paper:delete')")
    @Log(title = "试卷管理", businessType = BusinessType.DELETE)
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "试卷息的删除接口（通过id号删除）",
                  notes = "删除试卷信息[t_exam_paper]，作者：lin keqing")
    public RestResponse delete(@PathVariable Integer id) {
        ExamPaper examPaper = examPaperService.selectById(id);
        examPaper.setDeleted(true);
        examPaperService.updateByIdFilter(examPaper);
        return RestResponse.ok();
    }

    @PreAuthorize("@ss.hasPermi('exam:paper:update')")
    @Log(title = "试卷管理", businessType = BusinessType.UPDATE)
    @RequestMapping(value="/changeStatus/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "某张试卷的启用状态改变接口（禁用/启用）",
                  notes = "改变某张试卷的启用状态[t_exam_paper]，作者：lin keqing")
    public RestResponse<Integer> changeStatus(@PathVariable Integer id) {
        ExamPaper examPaper = examPaperService.selectById(id);
        ExamPaperStatusEnum examPaperStatusEnum = ExamPaperStatusEnum
                .fromCode(examPaper.getIsEnabled());
        Integer newStatus = examPaperStatusEnum == ExamPaperStatusEnum.Enable ?
                    ExamPaperStatusEnum.Disable.getCode() :
                    ExamPaperStatusEnum.Enable.getCode();
        examPaper.setIsEnabled(newStatus);
        examPaperService.updateByIdFilter(examPaper);
        return RestResponse.ok(newStatus);
    }
}
